import { RelTypeEnum } from '../annotation/RelTypeEnum'
import { ColumnType } from './ColumnType'
import { TableStruct, TableStructCache } from './TableStructCache'

const TAG = "SqlBuilder"

export default class SqlBuilder {
  // let sql = 'CREATE TABLE IF NOT EXISTS TaskConfig (' +
  // 'ID INTEGER PRIMARY KEY AUTOINCREMENT, ' +
  // 'type TEXT NOT NULL, ' +
  // 'AGE INTEGER, ' +
  // 'SALARY REAL, ' +
  // 'CODES BLOB)'

  private _table: string
  private _id: string
  private _fileds: string[] = []
  private _sql: string

  constructor() {
  }

  table(tableName) {
    this._table = tableName
    return this
  }

  id(field = 'id', autoincrement = true) {
    this._id = `${field} INTEGER PRIMARY KEY ${autoincrement ? 'AUTOINCREMENT' : ''}`
    return this
  }

  filed(filedName: string, type: ColumnType) {
    this._fileds.push(`${filedName} ${type}`)
    return this
  }

  buildTableSql() {
    if (!this._id) {
      this.id()
    }
    this._fileds.push(this._id)
    let result = `CREATE TABLE IF NOT EXISTS ${this._table}(${this._fileds.join()})`
    console.log("sql result:", result)
    return result
  }

  /**
   * 获取表结构创建语句
   * @param clazzName 类名
   * @returns
   */
  public static getCreateTabelSql(clazzName: string): string {
    // let sql = 'CREATE TABLE IF NOT EXISTS TaskConfig (' +
    // 'ID INTEGER PRIMARY KEY AUTOINCREMENT, ' +
    // 'type TEXT NOT NULL, ' +
    // 'AGE INTEGER, ' +
    // 'SALARY REAL, ' +
    // 'CODES BLOB)'

    // CJLogUtil.info(TAG, "tableMaps：", JSON.stringify(TableStructCache.tableMaps.get(clazzName)))
    // CJLogUtil.info(TAG, "structMaps：", JSON.stringify(TableStructCache.structMaps.get(clazzName)))
    const results = []
    // 获取表名
    const tableName = TableStructCache.tableMaps.get(clazzName)
    results.push(`CREATE TABLE IF NOT EXISTS ${tableName} (`)
    // 获取结构
    const colums = []
    const structs = TableStructCache.structMaps.get(clazzName)
    structs.forEach((item: TableStruct, index: number) => {
      if (item.isId == true) {
        colums.push(`${item.columnName} ${item.type} PRIMARY KEY ${item.autoincrement ? 'AUTOINCREMENT' : ''}`)
      } else {
        colums.push(`${item.columnName} ${item.type}`)
      }
    })
    results.push(colums.join(','))
    results.push(')')
    return results.join('')
  }

  //TODO 完善中
  public static getQuerySql(clazzName: string): string {
    const results = []
    // 1、检测结构
    // 获取表名
    const tableName = TableStructCache.tableMaps.get(clazzName)
    const structs = TableStructCache.structMaps.get(clazzName)


    for (let index = 0;index < structs.length; index++) {
      let item = structs[index]
      if (item.relType == RelTypeEnum.ONE_TO_ONE) { // 一对一

      }
    }

    return results.join('')
  }

  private buildTableUnionSql(curr: TableStruct, father: TableStruct): string {
    
    return
  }
}